package com.emip.config;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class CommonOperation {
	private static CommonOperation instance;
	
	private CommonOperation() {
		mapper = new ObjectMapper();
	}
	
	public static synchronized CommonOperation getInstance()
	{
		if (instance==null)
		    instance=new CommonOperation();
		  return instance;  
	}
	
	private static ObjectMapper mapper;
	
	//JSON String Converter
	public static String WriteJSONString(Object obj) {
		String result = "";
		try {
			result = mapper.writeValueAsString(obj);
		} catch (JsonGenerationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}
	
	//自定义execute SQL
	public static void executeSQL(Connection conn, String sql) {
		Statement st = null;
		try {
			st=conn.createStatement();
			st.execute(sql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (st != null)
					st.close();
				if (conn != null)
					conn.close();
			} catch (SQLException e) {
				System.out.println(e.toString());
			}

		}
	}
	
	//自定义query sql
	public static ResultSet querySQL(Connection conn, String sql) {
		Statement st = null;
		try {
			st=conn.createStatement();
			return st.executeQuery(sql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (st != null)
					st.close();
				if (conn != null)
					conn.close();
			} catch (SQLException e) {
				System.out.println(e.toString());
			}

		}
		return null;
	}
	
	//自定义executeUpdate
	public static int executeUpdateSQL(Connection conn, String sql) {
		Statement st = null;
		try {
			st=conn.createStatement();
			return st.executeUpdate(sql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return 0;
		} finally {
			try {
				if (st != null)
					st.close();
				if (conn != null)
					conn.close();
			} catch (SQLException e) {
				System.out.println(e.toString());
			}

		}
	}
}
